//
//  NSFileManager+ZLCategory.m
//  ZLCategory
//
//  Created by zhaozl on 2022/3/7.
//

#import "NSFileManager+ZLCategory.h"

@implementation NSFileManager (ZLCategory)

// 创建文件夹，及中间文件夹
+ (BOOL)zl_createDirectory:(NSString *)path {
    if (path == NULL || path.length == 0) {
        return NO;
    }
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return YES;
    }
    NSError *error = nil;
    if ([[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
        if (error) {
            NSLog(@"文件夹创建失败：%@", [error localizedDescription]);
        }
        return NO;
    }
    
    return YES;
}

// 创建文件
+ (BOOL)zl_createFile:(NSString *)path {
    if (path == NULL || path.length == 0) {
        return NO;
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return YES;
    }
    
    if ([[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil] == NO) {
        NSLog(@"文件创建失败：%@", path);
        return NO;
    }
    
    return YES;
}

// home
+ (NSString *)zl_getHomeDirectory {
    return NSHomeDirectory();
}

// Documents
+ (NSString *)zl_getDocumentDirectory {
    NSArray *pArySearch = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    if ([pArySearch count] < 1) {
        return NULL;
    }
    return [pArySearch objectAtIndex:0];
}

// library路径 /Library
+ (NSString *)zl_getLibraryDirectory {
    NSArray *libraryArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    if ([libraryArray count] < 1) {
        return nil;
    }
    
    return [libraryArray objectAtIndex:0];
}


// 缓存文件的路径 /Library/Caches
+ (NSString *)zl_getCachesDirectory {
    NSArray *pArySearch = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    
    if ([pArySearch count] < 1) {
        return NULL;
    }
    return [pArySearch objectAtIndex:0];
}

// 公共偏好设置的路径 /Library/PreferencePanes
+ (NSString *)zl_getPreferencePanesDirectory {
    NSArray *pArySearch = NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES);
    
    if ([pArySearch count] < 1) {
        return NULL;
    }
    return [pArySearch objectAtIndex:0];
}

// 临时文件的路径 /tmp
+ (NSString *)zl_getTemporaryDirectory {
    return NSTemporaryDirectory();
}

// 获取用户信息文件夹   (foler为nil时，要设置为@""，否则系统默认设置为@"（null）")
+ (NSString *)zl_getHomePath:(NSString *)folder {
    if (folder == nil) {
        folder = @"";
    }
    NSString *folderName = [NSString stringWithFormat:@"%@",folder];
    NSString *pathString = [self zl_getHomeDirectory];
    NSString *folderString = [pathString stringByAppendingPathComponent:folderName];
    if ([self zl_createDirectory:folderString]) {
        return folderString;
    }
    return nil;
}

// 获取用户信息文件夹     (foler为nil时，要设置为@""，否则系统默认设置为@"（null）")
+ (NSString *)zl_getDocumentPath:(NSString *)folder {
    if (folder == nil) {
        folder = @"";
    }
    NSString *folderName = [NSString stringWithFormat:@"%@",folder];
    NSString *pathString = [self zl_getDocumentDirectory];
    NSString *folderString = [pathString stringByAppendingPathComponent:folderName];
    if ([self zl_createDirectory:folderString]) {
        return folderString;
    }
    return nil;
}

// library           (foler为nil时，要设置为@""，否则系统默认设置为@"（null）")
+ (NSString *)zl_getLibraryPath:(NSString *)folder {
    if (folder == nil) {
        folder = @"";
    }
    NSString *folderName = [NSString stringWithFormat:@"%@",folder];
    NSString *pathString = [self zl_getLibraryDirectory];
    NSString *folderString = [pathString stringByAppendingPathComponent:folderName];
    if ([self zl_createDirectory:folderString]) {
        return folderString;
    }
    
    return nil;
}

// perferencespanes     (foler为nil时，要设置为@""，否则系统默认设置为@"（null）")
+ (NSString *)zl_getPreferencesPanesPath:(NSString *)folder {
    if (folder == nil) {
        folder = @"";
    }
    NSString *folderName = [NSString stringWithFormat:@"%@",folder];
    NSString *pathString = [self zl_getPreferencePanesDirectory];
    NSString *folderString = [pathString stringByAppendingPathComponent:folderName];// nil即为空
    if ([self zl_createDirectory:folderString]) {
        return folderString;
    }
    
    return nil;
}

// cache         (foler为nil时，要设置为@""，否则系统默认设置为@"（null）")
+ (NSString *)zl_getCachesPath:(NSString *)folder {
    if (folder == nil) {
        folder = @"";
    }
    NSString *folderName = [NSString stringWithFormat:@"%@",folder];
    NSString *pathString = [self zl_getCachesDirectory];
    NSString *folderString = [pathString stringByAppendingPathComponent:folderName];// nil即为空
    if ([self zl_createDirectory:folderString]) {
        return folderString;
    }
    
    return nil;
}

// temp          (foler为nil时，要设置为@""，否则系统默认设置为@"（null）")
+ (NSString *)zl_getTempPath:(NSString *)folder {
    if (folder == nil) {
        folder = @"";
    }
    
    NSString *folderName = [NSString stringWithFormat:@"%@",folder];
    NSString *pathString = [self zl_getTemporaryDirectory];
    NSString *folderString = [pathString stringByAppendingPathComponent:folderName];// nil即为空
    if ([self zl_createDirectory:folderString]) {
        return folderString;
    }
    
    return nil;
}

/// app路径
+ (NSString *)zl_getAppDirectoryPath {
    return [[NSBundle mainBundle] bundlePath];
}

/// 程序包内资源路径
/// @param resource 路径
+ (NSString *)zl_getMainBundleResource:(NSString *)resource {
    NSString *string = [NSString stringWithFormat:@"%@",resource];
    NSArray *array = [NSArray arrayWithArray:[string componentsSeparatedByString:@"."]];
    if (array.count != 2) {
        return nil;
    }
    return [[NSBundle mainBundle] pathForResource:[array objectAtIndex:0] ofType:[array objectAtIndex:1]];
}

/// 路径下为.plist文件，直接读写操作
/// @param path 路径
/// @param object 对象
/// @param key 键值
+ (BOOL)zl_setDicPath:(NSString *)path object:(id)object forKey:(NSString *)key {
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        if ([self zl_createFile:path] == NO) {
            // 创建失败
            return NO;
        }
    }
    
    if (key == NULL || key.length == 0) {
        return NO;
    }
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    
    if (dic == NULL) {
        dic = [NSMutableDictionary dictionaryWithCapacity:1];
    }
    
    if (object) {
        [dic setObject:object forKey:key];
    } else {
        [dic removeObjectForKey:key];
    }
    
    return [dic writeToFile:path atomically:YES];
}

/// 路径下为.plist文件，直接读写操作
/// @param path 路径
/// @param key 键值
+ (id)zl_getDicPath:(NSString *)path key:(NSString *)key {
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        if ([self zl_createFile:path] == NO) {
            //创建失败
            return NULL;
        }
    }
    
    if (key == NULL || key.length == 0) {
        return NULL;
    }
    NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:path];
    
    if (dic == NULL) {
        return NULL;
    }
    return [dic objectForKey:key];
}

/// 文件夹大小
/// @param path 路径
+ (CGFloat)zl_directorySizeAtPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }
    NSEnumerator *childFilesEnumerator = [[[NSFileManager defaultManager] subpathsAtPath:path] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString* fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
        if ([manager fileExistsAtPath:fileAbsolutePath]){
            folderSize += [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
        }
    }
    
    return folderSize / (1024.0 * 1024.0);
}

/// 文件大小
/// @param path 路径
+ (CGFloat)zl_fileSizeAtPath:(NSString *)path {
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil] fileSize] / (1024.0 * 1024.0);
    }
    
    return 0;
}

/// 删除文件\文件夹
/// @param path 路径
+ (BOOL)zl_delFiles:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:path]) {
        return [fileManager removeItemAtPath:path error:nil];
    }
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:path error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        [fileManager removeItemAtPath:[path stringByAppendingPathComponent:filename] error:NULL];
    }
    NSError *error;
    BOOL result = [fileManager removeItemAtPath:path error:&error];
    if (error) {
        return NO;
    }
    return YES;
}

/// 获取BUNDLE资源文件
/// @param bundlePath BUNDLE路径
/// @param file 文件名称
+ (NSString *)zl_getFileFromBundle:(NSString *)bundlePath file:(NSString *)file {
    NSString *string1 = [NSString stringWithFormat:@"%@",bundlePath];
    NSArray *array1 = [NSArray arrayWithArray:[string1 componentsSeparatedByString:@"."]];
    if (array1.count != 2) {
        return nil;
    }
    
    NSString *string2 = [NSString stringWithFormat:@"%@",file];
    NSArray *array2 = [NSArray arrayWithArray:[string2 componentsSeparatedByString:@"."]];
    if (array2.count != 2) {
        return nil;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:[array1 objectAtIndex:0] ofType:[array1 objectAtIndex:1]];
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    NSString * strPath = [bundle pathForResource:[array2 objectAtIndex:0] ofType:[array2 objectAtIndex:1]];
    return strPath;
}

/// home目录
/// @param folder folder
/// @param fileName 文件名称
+ (NSString *)zl_getHomeFolder:(NSString *)folder file:(NSString *)fileName {
    NSString *folderPath = [NSString stringWithFormat:@"%@",[self zl_getHomePath:folder]];
    if (fileName == NULL || fileName.length == 0) {
        return folderPath;
    }
    
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    return filePath;
}

/// home/library
/// @param folder folder
/// @param fileName 文件名称
+ (NSString *)zl_getLibraryFolder:(NSString *)folder file:(NSString *)fileName {
    NSString *folderPath = [NSString stringWithFormat:@"%@",[self zl_getLibraryPath:folder]];
    if (fileName == NULL || fileName.length == 0) {
        return folderPath;
    }
    
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    return filePath;
}

/// home/library/preferences
/// @param folder folder
/// @param fileName 文件名称
+ (NSString *)zl_getPreferencesPanesFolder:(NSString *)folder file:(NSString *)fileName {
    NSString *folderPath = [NSString stringWithFormat:@"%@",[self zl_getPreferencesPanesPath:folder]];
    if (fileName == NULL || fileName.length == 0) {
        return folderPath;
    }
    
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    return filePath;
}

/// home/library/caches
/// @param folder folder
/// @param fileName 文件名称
+ (NSString *)zl_getCachesFolder:(NSString *)folder file:(NSString *)fileName {
    NSString *folderPath = [NSString stringWithFormat:@"%@",[self zl_getCachesPath:folder]];
    if (fileName == NULL || fileName.length == 0) {
        return folderPath;
    }
    
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    return filePath;
}

/// home/tmp
/// @param folder folder
/// @param fileName 文件名称
+ (NSString *)zl_getTempFolder:(NSString *)folder file:(NSString *)fileName {
    NSString *folderPath = [NSString stringWithFormat:@"%@",[self zl_getTempPath:folder]];
    if (fileName == NULL || fileName.length == 0) {
        return folderPath;
    }
    
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    return filePath;
}

/// 判断文件是否存在
/// @param filePath 文件路径
+ (BOOL)zl_hasFile:(NSString *)filePath {
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

@end
